import React, {useEffect, useState} from 'react'
import {NavigationStackScreenComponent} from 'react-navigation-stack'
import {
  View,
  Image,
  ImageSourcePropType,
  Text,
  TouchableOpacity,
  ImageBackground,
  Button,
  Platform,
  BackHandler,
} from 'react-native'
import Drawer from 'react-native-drawer'
import {commonStyle, definedColors, translateSize} from 'styles'
import {appHomeStyle} from './styles'
import assets from './assets'
import {Division, RadiusButton, Toast} from 'components'
import {useAuthorization, operate, loginOut, setLogin} from 'services/authorization'
import env from 'constants/env.json'
import {PosModule} from 'native-modules'
import {navigate, navigateReplace, navigator} from 'services/navigation'
import {Alert} from 'react-native'
import Loading from '../components/loading'
import pos from '../api/pos'

interface GridItem {
  title: string
  color: string
  icon: ImageSourcePropType
  onPress: () => void
}
interface SelectItem {
  name: string
  onPress: () => void
}

const AppHomeScreen: NavigationStackScreenComponent = props => {
  const {state} = useAuthorization()
  const [openDrawer, setOpenDrawer] = useState<boolean>(false)
  const [showSelect, setShowSelect] = useState<boolean>(false)
  const onBackAndroid = () => {
    Toast.show('请先退出登录！')
    return true
  }

  useEffect(() => {
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', onBackAndroid)
    }
    return () => {
      if (Platform.OS === 'android') {
        BackHandler.removeEventListener('hardwareBackPress', onBackAndroid)
      }
    }
  }, [])

  useEffect(() => {
    let ss: any
    if (Platform.OS === 'android') {
      ss = props.navigation.addListener('willBlur', () => {
        BackHandler.removeEventListener('hardwareBackPress', onBackAndroid)
      })
    }
    return () => {
      if (Platform.OS === 'android') {
        ss && ss.remove()
      }
    }
  }, [])

  useEffect(() => {
    let ss: any
    if (Platform.OS === 'android') {
      ss = props.navigation.addListener('willFocus', () => {
        BackHandler.addEventListener('hardwareBackPress', onBackAndroid)
      })
    }
    return () => {
      if (Platform.OS === 'android') {
        ss && ss.remove()
      }
    }
  }, [])

  // 银联的调用不能并发
  let ylFlag = false

  const gridData: GridItem[][] = [
    [
      {
        title: '筹金',
        color: 'collect',
        icon: assets.images.icon_collect,
        onPress: () => {
          props.navigation.navigate('IDCardIdentity', {nextRouteName: 'BookList'})
        },
      },
      {
        title: '楼款',
        color: 'building',
        icon: assets.images.icon_building,
        onPress: () => {
          props.navigation.navigate('IDCardIdentity', {nextRouteName: 'FundList'})
        },
      },
    ],
    [
      {
        title: '定金',
        color: 'deposit',
        icon: assets.images.icon_deposit,
        onPress: () => {
          props.navigation.navigate('IDCardIdentity', {nextRouteName: 'CollectionCharges'})
        },
      },
      {
        title: '代收',
        color: 'instead',
        icon: assets.images.icon_instead,
        onPress: () => {
          props.navigation.navigate('IDCardIdentity', {nextRouteName: 'CollectionCharges'})
        },
      },
    ],
    [
      {
        title: '预收',
        color: 'advance',
        icon: assets.images.icon_advance,
        onPress: () => {
          props.navigation.navigate('IDCardIdentity', {nextRouteName: 'CollectionCharges'})
        },
      },
      {
        title: '更多',
        color: 'more',
        icon: assets.images.icon_more,
        onPress: () => {
          props.navigation.navigate('IDCardIdentity', {nextRouteName: 'CollectionCharges'})
        },
      },
    ],
    // [
    //   {
    //     title: '收暂收款',
    //     icon: assets.images.icon_temporary_payment,
    //     onPress: () => {
    //       props.navigation.navigate('IDCardIdentity', {nextRouteName: 'ChooseCustomer'})
    //     },
    //   },
    //   {
    //     title: '收补差款',
    //     icon: assets.images.icon_arrears,
    //     onPress: () => {
    //       props.navigation.navigate('IDCardIdentity', {nextRouteName: 'FillingInFund'})
    //     },
    //   },
    //   {
    //     title: '撤销',
    //     icon: assets.images.icon_cancel,
    //     onPress: () => {
    //       props.navigation.navigate('CancelSignIn')
    //     },
    //   },
    // ],
    // [
    //   {
    //     title: '已收款项',
    //     icon: assets.images.icon_trade,
    //     onPress: () => {
    //       props.navigation.navigate('IDCardIdentity', {nextRouteName: 'TradeList'})
    //     },
    //   },
    //   {
    //     title: '签到',
    //     icon: assets.images.icon_sign,
    //     onPress: () => {
    //       if (ylFlag) return
    //       ylFlag = true
    //       PosModule.sign().finally(() => {
    //         ylFlag = false
    //       })
    //     },
    //   },
    //   {
    //     title: '换班',
    //     icon: assets.images.icon_balance,
    //     onPress: () => {
    //       if (ylFlag) return
    //       ylFlag = true
    //       PosModule.balance().finally(() => {
    //         ylFlag = false
    //       })
    //     },
    //   },
    // ],
    // [
    //   {
    //     title: '余额查询',
    //     icon: assets.images.icon_balance_ye,
    //     onPress: () => {
    //       if (ylFlag) return
    //       ylFlag = true
    //       PosModule.balanceYe().finally(() => {
    //         ylFlag = false
    //       })
    //     },
    //   },
    // ],
  ]

  const renderGridItem = (item: GridItem) => {
    return (
      <TouchableOpacity
        style={[appHomeStyle.gridItem, appHomeStyle[item.color]]}
        key={item.title}
        activeOpacity={0.8}
        onPress={() => {
          operate()
          item.onPress()
        }}>
        <View style={appHomeStyle.imgContainer}>
          {item.color !== 'more' && (
            <Image
              style={
                item.color === 'deposit' || item.color === 'instead'
                  ? appHomeStyle.payCenter
                  : appHomeStyle.payLeft
              }
              source={assets.images.icon_pay}
            />
          )}
          <Image style={appHomeStyle[item.color + 'Icon']} source={item.icon} />
        </View>
        <Text style={appHomeStyle.gridTitle}>{item.title}</Text>
      </TouchableOpacity>
    )
  }

  const renderGridRow = (data: GridItem[], index: number) => {
    return (
      <View key={index} style={commonStyle.containerColumn}>
        <View style={appHomeStyle.containerRow}>{data.map(item => renderGridItem(item))}</View>
      </View>
    )
  }

  const renderSelectRow = (item: SelectItem, index: number) => {
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => {
          console.log(item)
          setShowSelect(!showSelect)
        }}>
        <View key={index} style={appHomeStyle.selectItem}>
          <Text style={appHomeStyle.selectTitle}>{item.name}</Text>
        </View>
      </TouchableOpacity>
    )
  }

  return (
    <Drawer
      type="static"
      open={openDrawer}
      // Drawer 展开区域组件
      content={
        <View style={appHomeStyle.drawerContainer}>
          <View style={appHomeStyle.drawerItem}>
            <Text style={[appHomeStyle.drawerTitle, appHomeStyle.drawerActive]}>地产收款</Text>
          </View>
          <View style={appHomeStyle.drawerItem}>
            <Text style={appHomeStyle.drawerTitle}>物业收款</Text>
          </View>
          <View style={appHomeStyle.drawerItem}>
            <Text style={appHomeStyle.drawerTitle}>商业收款</Text>
          </View>

          <View
            style={{
              width: '100%',
              position: 'absolute',
              left: translateSize(32),
              bottom: translateSize(50),
            }}>
            <RadiusButton onPress={() => {}}>
              <Text
                style={{
                  color: definedColors.white,
                  fontSize: translateSize(28),
                }}>
                退出登录
              </Text>
            </RadiusButton>
          </View>
        </View>
      }
      // 响应区域双击可以打开抽屉
      acceptDoubleTap
      // styles 和 tweenHandler是设置向左拉后主内容区的颜色，相当于给主内容区加了一个遮罩
      styles={{
        mainOverlay: {
          backgroundColor: 'black',
          opacity: 0,
        },
      }}
      captureGestures={false}
      // 打开/关闭 Drawer所需要的时间
      tweenDuration={100}
      // 触发抽屉打开/关闭必须经过的屏幕宽度比例
      panThreshold={0.08}
      // Drawer打开后有边界距离屏幕右边界的距离
      openDrawerOffset={viewport => {
        return 100
      }}
      // 拉开抽屉的响应区域
      panOpenMask={0.2}
      // 如果为true, 则尝试仅处理水平滑动
      negotiatePan>
      <View style={commonStyle.containerColumn}>
        <View style={appHomeStyle.settingContainer}>
          <TouchableOpacity
            activeOpacity={0.8}
            onPress={() => {
              setOpenDrawer(!openDrawer)
            }}>
            <Image
              style={{width: translateSize(30), height: translateSize(32)}}
              source={assets.images.icon_drawer}
            />
          </TouchableOpacity>
          <TouchableOpacity
            activeOpacity={0.8}
            onPress={() => {
              setShowSelect(!showSelect)
            }}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
              }}>
              <Text style={appHomeStyle.projectText}>{state.project.name}</Text>
              <Image
                style={{width: translateSize(40), height: translateSize(40)}}
                source={assets.images.icon_arrow_down}
              />
            </View>
          </TouchableOpacity>
        </View>
        {/*<ImageBackground source={assets.images.home_bg} style={appHomeStyle.banner}>*/}
        {/*<TouchableOpacity*/}
        {/*style={appHomeStyle.setting}*/}
        {/*onPress={() => {*/}
        {/*operate()*/}
        {/*props.navigation.navigate('Setting')*/}
        {/*}}>*/}
        {/*<Image source={assets.images.icon_setting} />*/}
        {/*</TouchableOpacity>*/}
        {/*<View style={appHomeStyle.authContainer}>*/}
        {/*<Text style={appHomeStyle.projectText}>{state.userName}（用户）</Text>*/}
        {/*<View style={{flexDirection: 'row', width: '100%', overflow: 'hidden'}}>*/}
        {/*<Text style={appHomeStyle.projectText}>当前项目：</Text>*/}
        {/*<Text style={[appHomeStyle.projectText, {flex: 1}]}>{state.project.name}</Text>*/}
        {/*</View>*/}
        {/*</View>*/}
        {/*</ImageBackground>*/}
        {gridData.map((data, index) => renderGridRow(data, index))}
        {showSelect && (
          <View style={appHomeStyle.selectContainer}>
            {(state.projectList || []).map((item: SelectItem, index: number) =>
              renderSelectRow(item, index),
            )}
          </View>
        )}
      </View>
    </Drawer>
  )
}

AppHomeScreen.navigationOptions = props => {
  return {header: null}
}

export default AppHomeScreen
